package handler

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/spf13/pflag"
	"io"
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/zeromicro/go-zero/rest/httpx"
	"month/api/internal/logic"
	"month/api/internal/svc"
	"month/api/internal/types"
)

func FileUpHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.FileUpRequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		f, m, err := r.FormFile("file")
		name := r.FormValue("name")
		b, err := io.ReadAll(f)
		if err != nil {
			log.Println("读取文件失败")
			return
		}

		//判断上传的文件格式
		if strings.HasSuffix(m.Filename, "txt") || strings.HasSuffix(m.Filename, "png") || strings.HasSuffix(m.Filename, "mp4") {
			log.Println("文件上传只允许文本，图片，视频")
			return
		}

		//判断文件大小
		if m.Size > 5*1024*1024 {
			//如果文件大小超过5M
			log.Println("文件过大")
			return
		}

		url := aliOss(m.Filename, b, name)
		log.Println(url)

		pflag.Set("file", url)
		req.File = url

		l := logic.NewFileUpLogic(r.Context(), svcCtx)
		resp, err := l.FileUp(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}

// 阿里云oss存储
func aliOss(filename string, fileData []byte, name string) string {

	// 创建OSSClient实例。
	// yourEndpoint填写Bucket对应的Endpoint，以华东1（杭州）为例，填写为https://oss-cn-hangzhou.aliyuncs.com。其它Region请按实际情况填写。
	client, err := oss.New("https://oss-cn-shanghai.aliyuncs.com", "LTAI5tQmo52teJHNuBkHHUgA", "CJyAzJQIVWcjgYOlPGukUKeTQlMYKn")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// 填写存储空间名称，例如examplebucket。
	bucket, err := client.Bucket("yumo001")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// 将Byte数组上传至exampledir目录下的exampleobject.txt文件。
	err = bucket.PutObject(filename, bytes.NewReader(fileData))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	//添加水印
	bu := base64.URLEncoding.EncodeToString([]byte(name))

	return "https://yumo001.oss-cn-shanghai.aliyuncs.com/" + filename + "?x-oss-process=image/watermark,text_" + bu
}
